/**
 * 管理草稿（聊天窗口输入了一半没发出的内容）
 */
import { Service } from '@gnlab/utils'
import { MemSubject } from '@gnlab/utils/rx'
import StorageManager from '@/lib/storage'
import type { Services } from '@/services'

class DraftStorage extends StorageManager<Record<string, string>> {
  constructor(accountId: string) {
    super({
      topic: `chat-drafts-${accountId}`,
      defaults: {},
    })
  }
}

export class Drafts extends Service<Services> {
  private get auth() {
    return this.services.auth
  }

  private storage: DraftStorage | undefined

  private readonly _drafts = new MemSubject<Record<string, string>>({}) // contactId => draft text
  readonly drafts = this._drafts.asStream()

  async registered() {
    const accountId = await this.auth.accountId
    this.storage = new DraftStorage(accountId)
    this._drafts.next(this.storage.extract())
  }

  /**
   * 保存草稿，不传 content 或传空字符串会清除此联系人的草稿
   */
  save(contactId: string, content = '') {
    if (!this.storage) return
    const updated = { ...this.drafts.value }
    if (content) updated[contactId] = content
    else delete updated[contactId]
    this._drafts.next(updated)
    this.storage.save(updated)
  }

  clear(contactId: string) {
    this.save(contactId)
  }
}
